package com.example.tourism.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class TokenUtil {

    // 有效期设置
    public static final Long accessTokenTTL = 60 * 60 * 1000L; // 一小时
//    public static final Long accessTokenTTL =  10 * 1000L; // 10 秒
    public static final Long refreshTokenTTL = 7 * 24 * 60 * 60 * 1000L; // 七天
//    public static final Long refreshTokenTTL = 20* 1000L; // 七天
    // 密钥明文，应该从配置文件或环境变量中读取
    public static final String JWT_KEY = "TDDSPRINGBOOTPROJECT2024/10/23";

    // 获取UUID字符串
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    // 生成访问令牌
    public static String generateAccessToken(String Id, String subject) {
        return getJwtBuilder(subject, accessTokenTTL, Id).compact();
    }

    // 生成刷新令牌
    public static String generateRefreshToken(String Id,String subject) {
        return getJwtBuilder(subject, refreshTokenTTL,Id).compact();
    }

    // 解析JWT，获取Claims
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    // 验证Token是否过时
    public static boolean verifyToken(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody()
                .getExpiration()
                .after(new Date());
    }


    // 创建JwtBuilder实例
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String Id) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Date expDate = new Date(nowMillis + ttlMillis);
        return Jwts.builder()
                // 设置头部信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                // 设置主题信息(载荷)
                .setId(Id)                               // 设置ID
                .setSubject(subject)                       // 设置主题
                .setIssuer("TD")                           // 设置签发者
                .setIssuedAt(now)                          // 设置签发时间
                .signWith(signatureAlgorithm, secretKey)   // 设置签名算法和密钥
                .setExpiration(expDate);                   // 设置过期时间
    }

    // 生成加密后的密钥
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    //得到accessToken中储存的uid
    public static String getId(String accessToken) throws Exception {
        return parseJWT(accessToken).getId();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(parseJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5NTM0ZGFmZjQyNDc0ZWJmOGYzMjQ4ZTY2MWZiZDlkYSIsInN1YiI6IjI4MjI3Nzg3MzdAcXEuY29tIiwiaXNzIjoiVEQiLCJpYXQiOjE3MjU4ODIzNjEsImV4cCI6MTcyNjQ4NzE2MX0.ocNQpQhxxs-XzUdZ9r6yI57rS4IVTwzOkioKUZh8Wg0").getId());
    }
}
